package thread.poll;

import java.util.concurrent.*;

public class ExecutorsDemo1 {
    public static void main(String[] args) {
//        ExecutorService threadExecutor = Executors.newSingleThreadExecutor();     // 单个线程
//        ExecutorService threadExecutor = Executors.newFixedThreadPool(5);   // 固定大小线程池
//        ExecutorService threadExecutor = Executors.newCachedThreadPool();         // 可伸缩的线程池

        // 最大线程到底该如何定义
        // 1、CPU 密集型，几核，就是几，可以保持CPu的效率最高 !
        // 2、I0密集型 > 判断你程序中十分耗IO的线程
        // 程序 15个大型任务 io十分占用资源 !
        int processors = Runtime.getRuntime().availableProcessors();

        ExecutorService threadExecutor =new ThreadPoolExecutor(2,
                5,
                processors,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(3),
                Executors.defaultThreadFactory(),
//                new ThreadPoolExecutor.AbortPolicy()                  // 超出范围，抛出异常
//                new ThreadPoolExecutor.DiscardOldestPolicy()          // 超出范围，尝试竞争
                new ThreadPoolExecutor.CallerRunsPolicy()             // 超出范围，回退任务
//                new ThreadPoolExecutor.DiscardPolicy()                // 超出范围，丢弃任务
        );

        try {
            for (int i = 1; i <= 9; i++) {
                threadExecutor.execute(()->{
                    System.out.println(Thread.currentThread().getName() + " OK");
                });
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            threadExecutor.shutdown();
        }
    }
}
